﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using VoiceMessager.Stream;

namespace VoiceMessager
{
	public class Udp
	{
		public event EventHandler<OnReciveEventArgs> OnRecive;
		private readonly UdpClient _udpClient;
		private IPEndPoint _serverPoint;

		public Udp(IPEndPoint ipEndPoint)
		{
			_udpClient = new UdpClient();
			_serverPoint = ipEndPoint;
			_udpClient.Connect(_serverPoint);
			
			_udpClient.BeginReceive(ReciveCallback, null);

		}

		private void ReciveCallback(IAsyncResult ar)
		{
			var x = _udpClient.EndReceive(ar,ref _serverPoint);
			OnRecive?.Invoke(this, new OnReciveEventArgs
			{
				ReviceBytes = x
			});
			_udpClient.BeginReceive(ReciveCallback, null);
		}


		public void Send(SendStream sendStream)
		{
			var bytes = sendStream.GetBytes();
			_udpClient.BeginSend(bytes, bytes.Length, RequestCallback, null);
		}

		private void RequestCallback(IAsyncResult ar)
		{
			_udpClient.EndSend(ar);
		}


	}

	public class OnReciveEventArgs : EventArgs
	{
		public Byte[] ReviceBytes { get; set; }
	}
}
